package com.tpvlog.seckill.common;

import redis.clients.jedis.Jedis;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理单个Jedis实例的组件
 */
public class JedisManager {

    /**
     * 一个Redis实例在这里就一个Jedis实例
     */
    private ConcurrentHashMap<String, Jedis> jedisMap =
            new ConcurrentHashMap<String, Jedis>();

    /**
     * 管理组件自己本身是单例
     */
    private JedisManager() {

    }

    static class Singleton {

        static JedisManager instance = new JedisManager();

    }

    public static JedisManager getInstance() {
        return Singleton.instance;
    }

    /**
     * 获取Jedis实例，同时进行缓存
     * @param host redis实例地址
     * @param port redis实例端口号
     * @return
     */
    public Jedis getJedis(String host, Integer port) {
        String cacheKey = host + port;

        if(jedisMap.get(cacheKey) == null) {
            synchronized(this) {
                if(jedisMap.get(cacheKey) == null) {
                    Jedis jedis = new Jedis(host, port);
                    jedisMap.put(cacheKey, jedis);
                }
            }
        }

        return jedisMap.get(cacheKey);
    }

    /**
     * 获取默认的jedis实例
     * @return
     */
    public Jedis getJedis() {
        return getJedis("127.0.0.1", 6379);
    }

}
